﻿// **********************************************************************
//
// Author: KingSley
// Email:3268374537@qq.com
// Created:	2018/8/1   09:00
// Introduce: 非继承MonoBehaviour的单例继承此类，并加入私有构造函数
//
// **********************************************************************
using System.Reflection;
using System;

namespace KingSley
{
    public class TSingleton<T> where T : class
    {
        private static T _instance;
        private static readonly object syslock = new object();
        public static readonly Type[] EmptyTypes = new Type[0];
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (syslock)
                    {
                        if (_instance == null)
                        {
                            ConstructorInfo ci = typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, EmptyTypes, null);
                            if (ci == null) { throw new InvalidOperationException("类必须包含私有构造函数!!!"); }
                            _instance = (T)ci.Invoke(null);
                        }
                    }
                }
                return _instance;
            }
        }
    }
}
